package cn.iocoder.yudao.module.iot.gateway.protocol.tcp.detector;

import java.util.*;

public class CompositeProtocolDetector  implements ProtocolDetector {
    private final List<ProtocolDetectionStrategy> strategies;

    public CompositeProtocolDetector() {
        this.strategies = new ArrayList<>();
    }

    public void addStrategy(ProtocolDetectionStrategy strategy) {
        strategies.add(strategy);
        // 按优先级排序
        strategies.sort(Comparator.comparingInt(ProtocolDetectionStrategy::getPriority));
    }

    @Override
    public String detectProtocol(byte[] data) {
        // 按优先级顺序尝试所有策略
        for (ProtocolDetectionStrategy strategy : strategies) {
            String protocol = strategy.detectProtocol(data, null);
            if (protocol != null && !protocol.isEmpty()) {
                return protocol;
            }
        }
        return "default";
    }

    @Override
    public Set<String> getSupportedProtocols() {
        // 收集所有支持的协议类型
        Set<String> protocols = new HashSet<>();
        for (ProtocolDetectionStrategy strategy : strategies) {
            protocols.addAll(strategy.getSupportedProtocols());
        }
        return protocols;
    }
}
